/** @format */

import { createVNode, render, App } from 'vue';
import Dialog401Component from './Index.vue';

interface Dialog401Options {
  visible?: boolean;
  onConfirm?: () => void;
  onCancel?: () => void;
  redirectUrl?: string;
}

interface Dialog401Instance {
  close: () => void;
}

const Dialog401 = (options: Dialog401Options = {}): Dialog401Instance => {
  // 创建容器
  const container = document.createElement('div');

  // 创建VNode
  const vnode = createVNode(Dialog401Component, {
    ...options,
    visible: true,
    onConfirm: () => {
      try {
        // 调用用户传入的确认回调
        options.onConfirm?.();
        // 移除组件
        render(null, container);
        document.body.removeChild(container);
      } catch (error) {
        console.error('Error in onConfirm callback:', error);
      }
    },
    onCancel: () => {
      try {
        // 调用用户传入的取消回调
        options.onCancel?.();
        // 移除组件
        render(null, container);
        document.body.removeChild(container);
      } catch (error) {}
    },
  });

  // 渲染组件
  render(vnode, container);

  // 确保元素存在后再添加到body
  const element = container.firstElementChild;
  if (element) {
    console.log(
      '登录已过期 ===>',
      document.querySelector('.dialog-401-overlay'),
    );
    if (!document.querySelector('.dialog-401-overlay')) {
      document.body.appendChild(element);
    }
    // document.body.appendChild(element);
  } else {
    console.error(
      'Dialog401 component rendering failed: No element was created',
    );
  }

  // 返回实例
  return {
    close: () => {
      const vm = vnode.component?.proxy;
      if (vm && typeof (vm as any).handleClose === 'function') {
        (vm as any).handleClose();
      }
      // 移除组件
      render(null, container);
      if (container.parentNode) {
        document.body.removeChild(container);
      }
    },
  };
};

// 用于Vue插件安装
Dialog401.install = (app: App): void => {
  app.config.globalProperties.$dialog401 = Dialog401;
};

export default Dialog401;
